{% extends "base.html" %}

{% block meta %}
    <meta name="menu-tag" content="41"/>
{% end block %}

{% block stylesheet %}
<link rel="stylesheet" type="text/css" href="{{static_url('css/bootstrap-markdown.min.css')}}">
<style type="text/css">
    #exp-container {
        margin: 0; 
        padding:0;
        overflow: hidden;
    }
</style>
{% end block %}

{% block main %}
<div style="height: 5px;"></div>

<div class="container" style="width: 100% !important">
    <!-- 左侧实验页面 -->
    <div class="col-md-8">
        <div id="exp-waiting">
            <div class="alert alert-info" id="exp-waiting-message">
                <p>实验环境准备中......</p>
            </div>
        </div>
        <div id="exp-container">
            <iframe width="100%" height="1000px" frameborder="0" scrolling="no" id="expframe"></iframe>
        </div>
    </div>
    <!-- 左侧可伸缩菜单栏结束 -->

    <!-- 右侧笔记页面 -->
    <div class="col-md-4">
        <ol class="breadcrumb">
            <li class="active">实验名称：<strong id="labname"></strong></li>
            <li class="active">学生学号：<strong>{{accountname}}</strong></li>
        </ol>
        <ul class="nav nav-tabs">
            <li class="active"><a href="#tab1" data-toggle="tab"><b>实验介绍</b></a></li>
            <li><a href="#tab2" data-toggle="tab"><b>实验文件</b></a></li>
        </ul>
        <div class="tab-content" style="min-height:500px">
            <div class="tab-pane active" id="tab1">
                <div class="panel panel-success">
                    <div class="panel-heading" id="lblSubmittedStatus">
                    </div>
                    <div class="panel-body">
                        <form>
                            <div name="content" data-provider="markdown-preview" data-iconlibrary="fa" id="markdown_content"></div>
                        </form>
                    </div>
                    <div class="panel-footer">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-md-2 control-label">得分：</label>
                                <div class="col-md-8">
                                    <input type="text" id="txtGrade" class="form-control" placeholder="0~100"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-md-2 control-label">评价：</label>
                                <div class="col-md-8">
                                    <textarea type="text" id="txtRemark" class="form-control" rows="5" cols="30"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-8 col-md-offset-2">
                                    <button type="button" id="btnReview" class='btn btn-sm btn-success'>提交</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="tab-pane" id="tab2">
                <div class="panel panel-primary" id="divStorages">
                    <div class="panel-heading">
                        当前路径：<b data-bind="text:current_path"></b>&nbsp;
                        <button class="btn btn-xs btn-info" title="返回上一级" data-bind="click:goParent, visible:current_path() != root_path">
                            <i class="fa fa-level-up"></i>
                        </button>
                    </div>
                    <div class="panel-body">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>名称</th> 
                                </tr>
                            </thead>
                            <tbody data-bind="foreach:storage_items">
                                <tr>
                                    <td>
                                        <b data-bind="text:name"></b>
                                        <button class="btn btn-xs btn-success" title="查看" data-bind="click:openFile, visible:viewerable()">
                                            <i class="fa fa-eye"></i>
                                        </button>
                                        <button class="btn btn-xs btn-info" title="进入" data-bind="click:$root.openDir, visible:isdir">
                                            <i class="fa fa-folder-open"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="panel-footer">
                        <button type="button" class="btn btn-sm  btn-primary" title="下载完整实验包" data-bind="click:download">
                            <i class="fa fa-download"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 文件浏览对话框开始 -->
<div id="dlgFileViewer" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content" style="width: 800px">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" id="lblFilePath"></h4>
            </div>
            <div class="modal-body">
                <iframe width="100%" height="800px" frameborder="0" scrolling="no" style="margin:0; padding:0" id="fileviewerFrame"></iframe>
            </div>
        </div>
    </div>
</div>
<!-- 文件浏览对话框结束 -->
{% end block %}


{% block script %}
<script src="{{static_url('js/bootstrap-markdown.js') }}" type="text/javascript"></script>
<script src="{{static_url('js/bootstrap-markdown.zh.js') }}" type="text/javascript"></script>
<script src="{{static_url('js/markdown.js') }}"></script>
<script src="{{static_url('js/to-markdown.js') }}"></script>

<script type="text/javascript">
    var accountName = '{{accountname}}';
    var labCode = '{{labcode}}';            // 该实验对应的代码号
    var labFile = '{{labfile}}';            // 实验主文件名
    var serviceName = '';                   // 该实验对应的容器服务名称
    var allowedFileTypes = [];              // 记录允许用户上传的文件类型(后缀名)，同时也是允许在浏览器中查看的文件类型
    var labStorage = new LabStorage();      // 用于knockout绑定的数据源
    var load_interval_id = 0;
    var load_retry_counts = 0;   

    /***********************************************/
    /* knockout数据源定义开始                        */
    /***********************************************/
    function LabStorage(){
        var self = this;
        self.root_path = labCode;
        self.storage_items = ko.observableArray();
        self.current_path = ko.observable(self.root_path);

        self.goParent = function(){
            current = self.current_path();
            index = current.lastIndexOf('/');
            if (index == -1){
                return;
            }
            parent = current.substr(0, index);
            self.current_path(parent);
            list_lab_items();
        };

        self.openDir = function(){
            storage_item = this;
            self.current_path(storage_item.path());
            list_lab_items();
        };

        self.download = function(){
            doDownload();
        };
    }

    function StorageItem(name, path, isdir){
        var self = this;
        self.name = ko.observable(name);
        self.path = ko.observable(path);
        self.isdir = ko.observable(isdir);

        self.viewerable = function(){
            var index = self.name().lastIndexOf('.');
            if (index == -1){
                return false;
            }
            ext = self.name().substr(index + 1);
            return (allowedFileTypes.indexOf(ext) == -1) ? false : true;
        }

        self.openFile = function(){
            var origin_url = $("#expframe").attr("src");
            var parent_path = origin_url.substr(0, origin_url.lastIndexOf('/'));
            parent_path = parent_path.replace('/notebooks/', '/edit/');
            var file_url = parent_path + '/' + this.name();
            $("#dlgFileViewer").modal({ 'backdrop': 'static' });
            $("#fileviewerFrame").attr("src", file_url);
            $("#lblFilePath").html(this.name())
        };
    }
    /***********************************************/
    /* knockout数据源定义结束                        */
    /***********************************************/

    $(document).ready(function(){
        // (1) 准备实验界面
        prepare_lab();

        // (2) 实验指导文本窗格处理
        var queryData = {
            'operation' : 'get_student_assignment_info',
            'operand' : {
                'accountname' : accountName,
                'labcode' : labCode
            }
        };
        $.ajax({
            url : '/class_assignments',
            type : 'post',
            data : JSON.stringify(queryData),
            dataType : 'json',
            success : function(jsonResult){
                var data = jsonResult.data;
                if (data.submitted){
                    $('<b class="text text-success">学生已提交本实验作业！</b>').appendTo($("#lblSubmittedStatus"));
                    if (data.reviewed){
                        $("#txtGrade").val(data.grade);
                        $("#txtRemark").val(data.remark);
                    }
                } else{
                    $('<b class="text text-danger">学生尚未提交本实验作业！</b>').appendTo($("#lblSubmittedStatus"));
                    $('#btnReview').attr('disabled', true);   
                }
                $("#labname").html(data.labname);

                //初始化编辑器
                $("#markdown_content").markdown({
                    language: 'zh',
                    hideable: true,
                    onShow: function(e){
                        var text = data.guides;
                        text = text.replace(/\\n\\r/g, "\n\r");
                        e.setContent(text);
                    }
                });

                $(document).click();                // 隐藏工具栏
            }
        });

        // (3) 实验文件清单装载
        var requestData = {
            'operation' : 'allowed_file_types',
            'accountname' : accountName
        };
        $.ajax({
            url: '/labstorage',
            type: "POST",
            data: JSON.stringify(requestData),
            dataType: 'JSON',
            success:function(jsonResult){
                allowedFileTypes = jsonResult.data;
                // 设定上传文件对话框支持的文件类型
                $("#dlgUploadFile_file").attr('accept', '.' + allowedFileTypes.join(',.'));
                // 装载文件清单并绑定
                list_lab_items();               
                ko.applyBindings(labStorage, document.getElementById("divStorages"));
            }
        });

        // （4）事件处理
        $("#btnReview").click(function(){
            var queryData = {
                'operation' : 'grade_assignment',
                'operand' : {
                    'accountname' : accountName,
                    'labcode' : labCode,
                    'grade' : $("#txtGrade").val(),
                    'remark' : $("#txtRemark").val()
                }
            };
            $.ajax({
                url : '/class_assignments',
                type : 'post',
                data : JSON.stringify(queryData),
                dataType : 'json',
                success : function(jsonResult){
                    if(jsonResult.success){
                       bootbox.alert('评分提交成功');
                    } else{
                        bootbox.alert(jsonResult.message);
                    }
                }
            });
        });
    });

    // 实验准备
    function prepare_lab(){
        // (1) 确保实验文件目录就绪
        var divMsg = $("#exp-waiting-message");
        $("<p>正在准备容器运行环境......</p>").appendTo(divMsg);
        var queryData = {
            'operation' : 'ensure_lab_container',
            'operand' : {
                'accountname' : accountName,
                'labcode' : labCode
            }
        };
        $.ajax({
            url : '/class_assignments',
            type : 'post',
            data : JSON.stringify(queryData),
            dataType : 'json',
            success : function(jsonResult){
                if(jsonResult.success){
                    $("<p>容器环境准备完毕</p>").appendTo(divMsg);
                    $("<p>正在进入实验界面......</p>").appendTo(divMsg);
                    serviceName = jsonResult.data;
                    load_jupyter_url();
                } else{
                    $("<p class='text text-danger'>" + jsonResult.message + "</p>").appendTo(divMsg);
                }
            }
        });
    }

    // 反复尝试装载jupyter notebook url
    function load_jupyter_url(){
        if (load_retry_counts >= 5){
            window.clearInterval(load_interval_id);
            $("<p class='text text-danger'>实验界面响应超时，请稍后重试刷新页面！</p>").appendTo($("#exp-waiting-message"));
            return;
        }
        var queryData = {
            'operation' : 'check_notebook_ready',
            'operand' : {
                'servicename' : serviceName,
                'accountname' : accountName
            }
        };
        $.ajax({
            url : '/class_assignments',
            type : 'post',
            data : JSON.stringify(queryData),
            dataType : 'json',
            success : function(jsonResult){
                load_retry_counts++;
                if (jsonResult.data){
                    window.clearInterval(load_interval_id);
                    $("#exp-waiting").hide();
                    $('#expframe').attr('src', jsonResult.data + labCode + '/' + labFile);
                } else{
                    if (load_interval_id == 0){
                        load_interval_id = window.setInterval(load_jupyter_url, 5000);
                    }
                }
            }
        });
    }

    // 获取当前目录下所有文件和子目录
    function list_lab_items(){
        var requestData = {
            operation : 'list_items',
            accountname : accountName,
            path : labStorage.current_path()
        };

        $.ajax({
            url : '/labstorage', 
            type : 'POST', 
            dataType : 'JSON',
            data : JSON.stringify(requestData),
            success : function(jsonResult){
                if (!jsonResult.success){
                    console.log(jsonResult.message);
                } else{
                    var arr = [];
                    for(var i=0;i<jsonResult.data.length;i++){
                        item = jsonResult.data[i];
                        arr.push(new StorageItem(item.name, item.path, item.isdir))
                    }
                    labStorage.storage_items(arr);
                }
            }
        });
    }

    // 打包下载实验文件
    function doDownload(){
        var url = '/labstorage_download';
        var form = $("<form></form>").attr("action", url).attr("method", "get");
        form.append($("<input></input>").attr("type", "hidden").attr("name", "accountname").attr("value", accountName));
        form.append($("<input></input>").attr("type", "hidden").attr("name", "labcode").attr("value", labCode));
        form.appendTo('body').submit().remove();
    }
            
</script>
{% end block %}
